<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
<!-- <script type="text/javascript" src="config.js"></script> -->
<style>
	* {
		background-color: transparent;
		color: rgba(255, 0, 0, 0.4);
		-webkit-user-select: none; /* Safari, Chrome */
		-moz-user-select: none;    /* Firefox */
		-ms-user-select: none;     /* IE 10+ */
		user-select: none;         /* Standard */
	}

	html body {
		margin: 0px;
		padding: 0px;
		color: rgba(255, 0, 0, 0.1);
		/* border: 1px solid; */
		/*设置透明边框  transparent*/
		/* border-color: rgba(255,0,0,0.1); */
	}

	#headerbar {
		margin-bottom: 3px;
	}

	#divUiMain {
		width: 100%;
		margin: 0px;
		padding: 0px;
		/* background-color: #FFDDDD; */
	}

	.tmp_bgcolor {
		background-color: #FFDDDD;
	}

	.editing {
		background-color: #FFDDDD;
	}

	button {
		position: relative;
		/* position: absolute; */
		border-radius: 50%;
		margin: 1px;
		border: 2px solid;
		padding: 10px;
		min-width: 50px;
		min-height: 50px;
		/*设置透明边框  transparent*/
	}

	.wasd {
		/* position: relative; */
		border-radius: 10%;
		margin: 0px;
		padding: 10px;
		border: 2px solid;
		float: left;
	}

	.wasdcenter {
		position: absolute;
		border: 2px solid;
		border-radius: 50%;
		top: -5px;
		left: 0;
		width: 20px;
		height: 20px;
		cursor: pointer
	}

	#info {
		color: rgba(255, 0, 0);
		display: none;
	}
</style>

<center id="headerbar">
	<span>手柄操作：</span>
	<a href="javascript: vmhelper.close();">退出</a>　
	<a href="javascript: location.reload();">刷新</a>　
	<a href="javascript: layout_reset()">重置</a>　
	<a href="javascript: enter_editmode();" id="btnEdit">编辑</a>
</center>
<!-- <div id="divUiMain" class="tmp_bgcolor"> -->
<div id="divUiMain" onselectstart="return false;">

	<!-- 方向拖动区 -->
	<!--button id="wasd" class="wasd">
		<span id="info">
			在此区域拖动可控制方向(WASD模拟)<br>
			其它区域为鼠标控制<br>
			建议横屏使用
		</span>
		<div id="wasdcenter" class="wasdcenter">
		</div>
	</button-->

	<!-- 按键列表 -->
	<button id="mousel" ontouchstart="if(!editmode) vmhelper.sendlbutton(true);" ontouchend="if(!editmode) vmhelper.sendlbutton(false);">左键</button>
	<button id="mouser" ontouchstart="if(!editmode) vmhelper.sendrbutton(true);" ontouchend="if(!editmode) vmhelper.sendrbutton(false);">右键</button>
	<button id="showkbd" onclick="if(!editmode) vmhelper.showkeyboard();">键盘</button>
	<button id="desktop" onclick="if(!editmode) godesktop();">桌面</button>

	<!-- <button id="key_f11" data-jskeycode="122">F11</button> -->
	<button id="key_space" data-jskeycode="32">空格</button>
	<button id="key_ok" data-jskeycode="13">OK</button>

	<button id="key_W" data-jskeycode="87">W</button>
	<button id="key_A" data-jskeycode="65">A</button>
	<button id="key_S" data-jskeycode="83">S</button>
	<button id="key_D" data-jskeycode="68">D</button>

	<button id="key_B" data-jskeycode="66">B</button>
	<button id="key_C" data-jskeycode="67">C</button>
	<button id="key_V" data-jskeycode="86">V</button>
	
	<button id="key_H" data-jskeycode="72">H</button>
	<button id="key_Q" data-jskeycode="81">Q</button>
	<button id="key_E" data-jskeycode="69">E</button>

	<button id="key_U" data-jskeycode="85">U</button>
	<button id="key_I" data-jskeycode="73">I</button>
	<button id="key_O" data-jskeycode="79">O</button>

	<button id="key_L" data-jskeycode="76">L</button>
	<button id="key_J" data-jskeycode="74">J</button>
	<button id="key_K" data-jskeycode="75">K</button>

	<button id="key_Y" data-jskeycode="89">Y</button>
	<button id="key_Z" data-jskeycode="90">Z</button>
	<button id="key_P" data-jskeycode="80">P</button>
</div>


<script>

	const MIN_DRAG_AREA_SIZE=50;
	var loglevel=1;
	var PageWidth = window.innerWidth;
	var PageHeight = window.innerHeight;

	editmode = false;
	minDevSize = 30;
	empty_size = 50;
	page_paddinglt = 1;
	page_paddingr = 5;
	page_paddingb = 5;
	// 灵敏度
	mousemul = 2;

	setTimeout("hideinfo()", 3000);

	if (isNullObj(vmhelper)) {
		window.vmhelper = {
			sendmousemoveby: function (x, y) { },
			sendlbutton: function (isdown) { },
			sendrbutton: function (isdown) { },
			sendkeydown: function (jskeycode) { },
			sendkeyup: function (jskeycode) { },
			showkeyboard: function () { },
			readlayout: function () { },
			savelayout: function (strjs) { console.log(strjs); },
			log: function (msg) { console.log(msg); },
		};
	}

	function log(msg) {
		if(loglevel>0) vmhelper.log(msg);
	}

	function $(objid) {
		return document.getElementById(objid);
	}

	function isNullObj(obj) {
		if(obj == null) return true;
		if (typeof(obj) === "undefined") return true;
		return false;
	}

	function setpos(percentX, percentY, strObjId) {
		var obj = $(strObjId);
		if (isNullObj(obj)) {
			return;
		}
		obj.style.position = 'absolute';
		obj.style.left=percentX;
		obj.style.top =percentY;
	}

	function hideinfo() {
		var obj;
		obj = $('info');
		if (isNullObj(obj)) {
			return;
		}
		obj.style.display = "none";

		obj = $('divUiMain');
		obj.classList.remove('tmp_bgcolor');
	}

	var btnEdit = $('btnEdit');
	function enter_editmode() {
		if (!editmode) {
			editmode = true;
			btnEdit.innerText = "保存";
		} else {
			editmode = false;
			btnEdit.innerText = "编辑";
			vmhelper.savelayout(layout2js());
		}
	}

	function layout2js() {
		var xper, yper, obj, strjs;

		strjs = "loglevel="+loglevel+";\n\n";

		// obj = wasd;
		// xper = (obj.offsetLeft/PageWidth*100).toFixed(2) + "%"; if(xper.length < 6) xper = " " + xper;
		// yper = (obj.offsetTop/PageHeight*100).toFixed(2) + "%"; if(yper.length < 6) yper = " " + yper;
		// strjs += "setpos(\"" + xper + "\", \"" + yper + "\", '" + obj.id + "');\n";

		var btns = document.getElementsByTagName("button");
		var i;
		for (i = 0; i < btns.length; i++) {
			var btn = btns[i];
			if(btn.offsetLeft == "" || btn.offsetTop == "") {
				continue;
			}
			obj = btn;
			xper = (obj.offsetLeft/PageWidth*100).toFixed(2) + "%"; if(xper.length < 6) xper = " " + xper;
			yper = (obj.offsetTop/PageHeight*100).toFixed(2) + "%"; if(yper.length < 6) yper = " " + yper;
			strjs += "setpos(\"" + xper + "\", \"" + yper + "\", '" + obj.id + "');\n";
		}

		return strjs;
	}

	function layout_reset() {
		var strjs = vmhelper.getdefaultlayout();
		vmhelper.savelayout(strjs);
		location.reload();
	}

	// alt + D
	function godesktop() {
		vmhelper.sendkeydown(91);
		vmhelper.sendkeydown(68);
		vmhelper.sendkeyup(68);
		vmhelper.sendkeyup(91);
	}

	window.onload = function () {

		btnEdit.innerText = "编辑";
		var divUiMain = $('divUiMain');
		var wasd = $('wasd');
		var wasdcenter = $('wasdcenter');
		var bool_dragging_direction = false;
		var bool_dragging_mouse = false;
		var finger_dir = -1;
		var finger_mse = -1;
		var page_minsize = PageWidth;
		if (page_minsize > PageHeight) {
			page_minsize = PageHeight;
		}
		var drag_region_size = (page_minsize - empty_size) / 2;
		if (drag_region_size < MIN_DRAG_AREA_SIZE) drag_region_size = MIN_DRAG_AREA_SIZE;

		// divUiMain.style.top = 0 + "px";
		// divUiMain.style.height =  PageHeight - $('headerbar').style.offsetHeight+ "px";

		if (!isNullObj(wasd)) {
			wasd.style.width = drag_region_size + "px";
			wasd.style.height = drag_region_size + "px";
			wasdcenter.style.width = 30 + "px";
			wasdcenter.style.height = 30 + "px";

			wasdcenter.style.top = getcenterx_of(wasd) + "px";
			wasdcenter.style.left = getcentery_of(wasd) + "px";
		}

		// 自定义布局
		try {
			var strjs = vmhelper.readlayout();
			log("读取到：\n" + strjs);
			eval(strjs);
		} catch (error) {
			log(error.message);
		}
		// if (typeof custom_layout !== "undefined") {
		// 	custom_layout();
		// }
		// const script = document.createElement("script");
		// script.src = "config.js?t="+Math.random()*100000000;
		// document.body.appendChild(script);

		var last_mouse_x, last_mouse_y, last_juedu = -1;

		//事件
		var start = function (e) {

			var x, y, srcid, tagnm, which_pointer = 0;
			var i, len = e.changedTouches.length;
			for (i = 0; i < len; i++) {
				var touchevent = e.changedTouches[i];

				which_pointer = touchevent.identifier;
				srcid = touchevent.target.id;
				tagnm = touchevent.target.tagName.toUpperCase();
				x = touchevent.pageX;
				y = touchevent.pageY;

				log("touch start |name:" + tagnm + "|id:" + srcid + "|pointer:" + which_pointer); // 调试用，不要删除

				if (editmode) {

					if(tagnm != "BUTTON") {
						return;
					}

					log("开始移动编辑 " + srcid + " " + which_pointer);

					touchevent.target.classList.add('editing');
					touchevent.target.style.position = "absolute";

					// var orix = touchevent.target.style.left.replace("px", "");
					// var oriy = touchevent.target.style.top.replace("px", "");
					var orix = touchevent.target.offsetLeft;
					var oriy = touchevent.target.offsetTop;

					// if (orix == "") orix = x - (touchevent.target.offsetWidth / 2);
					// if (oriy == "") oriy = y - (touchevent.target.offsetHeight / 2);

					touchevent.target.edit_moving = true;
					touchevent.target.edit_startx = x;
					touchevent.target.edit_starty = y;
					touchevent.target.edit_offsetx = x - orix;
					touchevent.target.edit_offsety = y - oriy;
					log("原坐标：" + orix + ", " + oriy + ", " + touchevent.target.edit_offsetx + ", " + touchevent.target.edit_offsety);
					e.stopPropagation();

					return;
				}

				var b_stopPropagation = false;

				if (srcid == "wasd" || srcid == "wasdcenter") {
					b_stopPropagation = true;
					if (!bool_dragging_direction) {
						bool_dragging_direction = true;
						finger_dir = which_pointer;
						log("方向控制模拟开始 " + srcid + " " + which_pointer);
					}
				}
				if (srcid == "divUiMain" || tagnm == "BODY") {
					b_stopPropagation = true;
					if (!bool_dragging_mouse) {

						last_mouse_x = x;
						last_mouse_y = y;
						bool_dragging_mouse = true;
						finger_mse = which_pointer;
						log("鼠标控制模拟开始 " + srcid + " " + which_pointer);
					}
				}

				if (!isNullObj(touchevent.target.dataset.jskeycode)) {
					var jskeycode = touchevent.target.dataset.jskeycode;
					vmhelper.sendkeydown(jskeycode);
				}

				if (b_stopPropagation) {
					e.stopPropagation();
					// log("禁止事件传递");
				} else {
					// log("事件传递继续..");
				}
			}
		}
		var move = function (e) {
			var x, y, srcid, which_pointer = 0;
			var i, len = e.changedTouches.length;
			for (i = 0; i < len; i++) {
				var touchevent = e.changedTouches[i];
				// log(touchevent.target.id + " " + touchevent.identifier);
				which_pointer = touchevent.identifier;
				srcid = touchevent.target.id;

				x = touchevent.pageX;
				y = touchevent.pageY;

				var objmain, objblock;
				if (editmode && touchevent.target.edit_moving) {
					// log("正在移动编辑 " + srcid + " " + which_pointer);

					objmain = touchevent.target;
					var newleft = x - objmain.edit_offsetx;
					var newtop = y - objmain.edit_offsety;

					if (newleft < page_paddinglt) newleft = page_paddinglt;
					if (newtop < page_paddinglt) newtop = page_paddinglt;
					log("新坐标1：" + newleft + ", " + newtop);

					var parentl = 0; parentt = 0;
					if(objmain.offsetParent != null) {
						var parent_lefttop = getPosition(objmain.offsetParent);
						parentl = parent_lefttop.left;
						parentt = parent_lefttop.top;
					}

					if (parentl + newleft + objmain.offsetWidth + page_paddingr >= PageWidth) {
						newleft = PageWidth - parentl - objmain.offsetWidth - page_paddingr;
					}
					log("新坐标2：" + newleft + ", " + newtop);

					if (parentt + newtop + objmain.offsetHeight + page_paddingb >= PageHeight) {
						newtop = PageHeight - parentt - objmain.offsetHeight - page_paddingb;
					}

					log("新坐标3：" + newleft + ", " + newtop);

					objmain.style.left = newleft + "px";
					objmain.style.top = newtop + "px";

					return;
				}

				if (bool_dragging_direction && finger_dir == which_pointer) {
					log("方向控制 " + srcid + " " + which_pointer);
					objmain = wasd;
					objblock = wasdcenter;
					var newleft = x - getPosition(objmain).left; //小方块相对于父元素（长线条）的left值

					if (newleft >= objmain.offsetWidth - minDevSize) {
						newleft = objmain.offsetWidth - minDevSize;
					}
					if (newleft < 0) {
						newleft = 0;
					}
					objblock.style.left = newleft + "px";

					var newtop = y - getPosition(objmain).top; //小方块相对于父元素（长线条）的top值
					if (newtop >= objmain.offsetHeight - minDevSize) {
						newtop = objmain.offsetHeight - minDevSize;
					}
					if (newtop < 0) {
						newtop = 0;
					}
					objblock.style.top = newtop + "px";

					var center_left = getcenterx_of(wasd);
					var center_top = getcentery_of(wasd);

					// 计算角度
					var juedu = Math.atan2(newtop - center_top, newleft - center_left);
					juedu = juedu * 180 / Math.PI;
					juedu = (juedu < 0) ? (juedu * -1) : (360 - juedu);
					// juedu = parseInt(juedu);
					log("角度：" + juedu);

					// 传送按键事件
					send_fake_keyevent(juedu);

					last_juedu = juedu;

				} else if (bool_dragging_mouse && finger_mse == which_pointer) {
					log("鼠标控制 " + srcid + " " + which_pointer);
					var deltax = x - last_mouse_x;
					var deltay = y - last_mouse_y;
					if (mousemul > 0) {
						deltax *= mousemul;
						deltay *= mousemul;
					}
					vmhelper.sendmousemoveby(parseInt(deltax), parseInt(deltay));
					last_mouse_x = x;
					last_mouse_y = y;
				}

			}
		}
		var end = function (e) {
			var x, y, srcid, which_pointer = 0;
			var i, len = e.changedTouches.length;
			for (i = 0; i < len; i++) {
				var touchevent = e.changedTouches[i];
				// log(touchevent.target.id + " " + touchevent.identifier);
				which_pointer = touchevent.identifier;
				srcid = touchevent.target.id;
				x = touchevent.pageX;
				y = touchevent.pageY;

				log("end " + srcid + " " + which_pointer); // 调试用，不要删除

				if (editmode) {
					log("停止移动编辑 " + srcid + " " + which_pointer);
					touchevent.target.edit_moving = false;
					touchevent.target.classList.remove('editing');

					return;
				}

				if (finger_dir == which_pointer) {
					log("方向控制停止 " + srcid + " " + which_pointer);
					bool_dragging_direction = false;
					wasdcenter.style.top = getcenterx_of(wasd) + "px";
					wasdcenter.style.left = getcentery_of(wasd) + "px";
					finger_dir = -1;
					last_juedu = -1

					// 弹起所有方向键
					send_all_dirkeys_up();
				}
				if (finger_mse == which_pointer) {
					log("鼠标控制停止 " + srcid + " " + which_pointer);
					bool_dragging_mouse = false;
					finger_mse = -1;
				}

				if (!isNullObj(touchevent.target.dataset.jskeycode)) {
					var jskeycode = touchevent.target.dataset.jskeycode;
					vmhelper.sendkeyup(jskeycode);
				}
			}
		}


		var keydownlist = {
			w: false,
			a: false,
			s: false,
			d: false,
		};

		function send_fake_keyevent(juedu) {
			// last_juedu

			// # W
			if (juedu <= (90 + 22.5) && juedu >= (90 - 22.5)) {
				send_all_dirkeys_up("w");
				vmhelper.sendkeydown(87);
				// vmhelper.sendkeyup(87);
				keydownlist.w = true;
			}

			// # A
			if (juedu <= (180 + 22.5) && juedu >= (180 - 22.5)) {
				send_all_dirkeys_up("a");
				vmhelper.sendkeydown(65);
				// vmhelper.sendkeyup(65);
				keydownlist.a = true;
			}

			// # S
			if (juedu <= (270 + 22.5) && juedu >= (270 - 22.5)) {
				send_all_dirkeys_up("s");
				vmhelper.sendkeydown(83);
				// vmhelper.sendkeyup(83);
				keydownlist.s = true;
			}

			// # D
			if (juedu <= 22.5 || juedu >= (360 - 22.5)) {
				send_all_dirkeys_up("d");
				vmhelper.sendkeydown(68);
				// vmhelper.sendkeyup(68);
				keydownlist.d = true;
			}

			// D + W
			if (juedu <= (90 - 22.5) && juedu >= (22.5)) {
				send_all_dirkeys_up("dw");
				vmhelper.sendkeydown(87);
				vmhelper.sendkeydown(68);
				keydownlist.d = true;
				keydownlist.w = true;
			}
			// A + W
			if (juedu <= (180 - 22.5) && juedu >= (90 + 22.5)) {
				send_all_dirkeys_up("aw");
				vmhelper.sendkeydown(87);
				vmhelper.sendkeydown(65);
				keydownlist.a = true;
				keydownlist.w = true;
			}
			// A + S
			if (juedu <= (270 - 22.5) && juedu >= (180 + 22.5)) {
				send_all_dirkeys_up("as");
				vmhelper.sendkeydown(65);
				vmhelper.sendkeydown(83);
				keydownlist.a = true;
				keydownlist.s = true;
			}
			// S + D
			if (juedu <= (360 - 22.5) && juedu >= (270 + 22.5)) {
				send_all_dirkeys_up("sd");
				vmhelper.sendkeydown(83);
				vmhelper.sendkeydown(68);
				keydownlist.s = true;
				keydownlist.d = true;
			}


		}

		function send_all_dirkeys_up(excludes) {
			if (isNullObj(excludes)) { excludes = ""; }
			if (excludes.indexOf("w") === -1 && keydownlist.w) { vmhelper.sendkeyup(87); keydownlist.w = false; }
			if (excludes.indexOf("a") === -1 && keydownlist.a) { vmhelper.sendkeyup(65); keydownlist.a = false; }
			if (excludes.indexOf("s") === -1 && keydownlist.s) { vmhelper.sendkeyup(83); keydownlist.s = false; }
			if (excludes.indexOf("d") === -1 && keydownlist.d) { vmhelper.sendkeyup(68); keydownlist.d = false; }
		}

		function getcenterx_of(obj) {
			var result = ((obj.offsetWidth - minDevSize) / 2);
			return result;
		}
		function getcentery_of(obj) {
			return ((obj.offsetHeight - minDevSize) / 2);
		}

		//获取元素的绝对位置
		function getPosition(node) {
			var left = node.offsetLeft; //获取元素相对于其父元素的left值var left
			var top = node.offsetTop;
			current = node.offsetParent; // 取得元素的offsetParent
			// 一直循环直到根元素

			while (current != null) {
				left += current.offsetLeft;
				top += current.offsetTop;
				current = current.offsetParent;
			}
			return {
				"left": left,
				"top": top
			};
		}



		//鼠标按下方块
		if (!isNullObj(wasd)) {
			wasd.addEventListener("touchstart", start);
		}
		divUiMain.addEventListener("touchstart", start);
		window.addEventListener("touchmove", move);
		window.addEventListener("touchend", end);

		// 其它按钮
		window.addEventListener("touchstart", start);




	}


</script>
